package io.renren.modules.sys.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import io.renren.common.exception.RRException;
import io.renren.common.utils.RandomUtil;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.LineQcodeEntity;
import io.renren.modules.sys.service.LineQcodeService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.LinePasswordEntity;
import io.renren.modules.sys.service.LinePasswordService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.filechooser.FileSystemView;


/**
 * 线充
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-10-12 16:59:44
 */
@RestController
@RequestMapping("sys/linepassword")
public class LinePasswordController {
    @Autowired
    private LinePasswordService linePasswordService;
    @Autowired
    private LineQcodeService lineQcodeService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:linepassword:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = linePasswordService.queryPage(params);

        return R.ok().put("page", page);
    }



    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:linepassword:info")
    public R info(@PathVariable("id") Integer id){
        LinePasswordEntity linePassword = linePasswordService.getById(id);

        return R.ok().put("linePassword", linePassword);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:linepassword:save")
    public R save(@RequestBody LinePasswordEntity linePassword){
        linePasswordService.save(linePassword);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:linepassword:update")
    public R update(@RequestBody LinePasswordEntity linePassword){
        ValidatorUtils.validateEntity(linePassword);
        linePasswordService.updateById(linePassword);
        
        return R.ok();
    }
    /**
     * 上传
     */
    @RequestMapping("/saveUpload")
    public R saveUpload(String agentids, String salesid, String merchants, MultipartFile files) throws Exception {
        System.out.println(111111);
        if (files.isEmpty()) {
            throw new RRException("导入文件不能为空");
        }

        Workbook workbook = null;
        int totalNum = 0;
        String sn = RandomUtil.generateString(16);
        String path =  "C:\\" + sn+".xlsx";
        File file = new File(path);
        //获取到multipartFile文件输入流
        InputStream input = files.getInputStream();
        //FileCopyUtils.copy(multipartFile.getBytes(), file);
        workbook = WorkbookFactory.create(input);
        List<LinePasswordEntity> list = new ArrayList<LinePasswordEntity>();
        /*遍历sheet页*/
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            /*统计导入的总条数，要是你的excell包含了表头，就不用加1了*/
            if (sheet.getLastRowNum() > 0) {
                totalNum += sheet.getLastRowNum();
            }
            /*遍历行，这里j的初始值取1是因为我的表格里第一行是表头*/
            for (int j = 2; j < sheet.getPhysicalNumberOfRows(); j++) {
                Row row = sheet.getRow(j);
                /*解析列，下标从0开始*/
                Cell cell1 = row.getCell(0);

                if (cell1 == null||"".equals(cell1)) {
                    continue;
                }
                DecimalFormat df = new DecimalFormat("#");
                LinePasswordEntity entity = new LinePasswordEntity();
                entity.setDevicesn(cell1.toString());
                entity.setAgentid(Integer.valueOf(agentids));
                entity.setMerchant(Integer.valueOf(merchants));
                entity.setSalesid(salesid);
                list.add(entity);
            }
            /*持久化：批量新增*/
            linePasswordService.saveBatch(list);
        }
        /*解析完删除此路径下的文件*/

        file.delete();

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:linepassword:delete")
    public R delete(@RequestBody Integer ids){
        linePasswordService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/deleteById")
    public R deleteById(@RequestBody Integer id){
        linePasswordService.removeById(id);

        return R.ok();
    }

    /**
     * 下载模板
     * @param
     * @return
     */
    @RequestMapping("/formwork")
    public String downLoadAllCode(){
        String url = "C:\\Users\\Administrator\\Desktop";
//        ValidatorUtils.validateEntity(lineQcode);
//        java.util.List<LineQcodeEntity> list = lineQcodeService.list();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String[] headers = { "二维码编号"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell1 = row1.createCell(0);
        HSSFRichTextString richString1 =  new HSSFRichTextString("");
        cell1.setCellValue(richString1);


//        HSSFCell cell2 = row1.createCell(1);
//        HSSFRichTextString richString2 =  new HSSFRichTextString(shelvesname);
//        cell2.setCellValue(richString2);
//
//        HSSFCell cell3 = row1.createCell(3);
//        HSSFRichTextString richString3 =  new HSSFRichTextString("补货方式：");
//        cell3.setCellValue(richString3);
//
//        HSSFCell cell4 = row1.createCell(4);
//        HSSFRichTextString richString4 =  new HSSFRichTextString("补至库存上限");
//        cell4.setCellValue(richString4);
//
//        HSSFCell cell5 = row1.createCell(7);
//        HSSFRichTextString richString5 =  new HSSFRichTextString("日期：");
//        cell5.setCellValue(richString5);
//
//        HSSFCell cell6 = row1.createCell(8);
//        HSSFRichTextString richString6 =  new HSSFRichTextString(format.format(new Date()));
//        cell6.setCellValue(richString6);


        HSSFRow row = sheet.createRow(1);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }

        //遍历集合，将每个集合元素对象的每个值填充到单元格中
//        for(int i=0;i<list.size();i++){
////            LineQcodeEntity entity=list.get(i);
//            //从第二行开始填充数据
////            row = sheet.createRow(i+2);
//            //该集合只记录数量和时间，这两个值来自statisticsModel。如果对象比较复杂，需要额外转换，比如Date类型的日期，int，float类型的数值
//            List<String> datas=new ArrayList<>();
//
////            String qcode = entity.getQcode();
////            String barcode = entity.getBarcode();
////            String lowerLimit = entity.getLowerLimit().toString();
////            String upperLimit = entity.getUpperLimit().toString();
////            String stock = entity.getStock().toString();
////            String onshelves = entity.getOnshelves().toString();
////            String buycount = entity.getBuycount().toString();
////            String avgcost = entity.getAvgcost().toString();
////            String totalcost = entity.getTotalcost().toString();
////            datas.add(qcode);
////            datas.add(barcode);
////            datas.add(lowerLimit);
////            datas.add(upperLimit);
////            datas.add(stock);
////            datas.add(onshelves);
////            datas.add(buycount);
////            datas.add(avgcost);
////            datas.add(totalcost);
//            for (int j=0;j<datas.size();j++) {
//                String string=datas.get(j);
//                HSSFCell cell = row.createCell(j);
//                HSSFRichTextString richString = new HSSFRichTextString(string);
//                HSSFFont font3 = workbook.createFont();
//                //定义Excel数据颜色，这里设置为蓝色
//                font3.setColor(HSSFColor.BLUE.index);
//                richString.applyFont(font3);
//                cell.setCellValue(richString);
//            }
//
//        }
        String message = "";
        File desktopDir = FileSystemView.getFileSystemView()
                .getHomeDirectory();
        try {
            FileOutputStream fout = new FileOutputStream(url+"/"+"二维码编号模板.xls");
            workbook.write(fout);
            message = url+"/"+"二维码编号模板.xls成功,请到桌面查找！";
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
            message = "导出失败！";
        }

        return message;
    }

}
